package com.archstoday.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;

import com.xw.repo.refresh.Pullable;

/**
 * Created by vieboo on 2017/7/31.
 */

public class PullScrollView extends ScrollView implements Pullable {

    private boolean pullDownEnable = true; //下拉刷新开关
    private boolean pullUpEnable = true; //上拉刷新开关

    private int currentY = 0;
    private boolean isBottom = false;

    public PullScrollView(Context context) {
        super(context);
    }

    public PullScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PullScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setPullUp(boolean ifPullUp) {
        pullUpEnable = ifPullUp;
    }


    @Override
    public boolean canPullDown() {
        if (!pullDownEnable) {
            return false;
        }
        if (currentY == 0) {
            return true;
        }

        return false;
    }

    @Override
    public boolean canPullUp() {
        if (!pullUpEnable) {
            return false;
        }
        if (isBottom) {
            // 没有item的时候也可以上拉加载
            return true;
        }
        return false;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        View view = getChildAt(getChildCount() - 1);
        int d = view.getBottom();
        d -= getHeight() + getScrollY();
        if (d == 0) {
            isBottom = true;
        } else {
            super.onScrollChanged(l, t, oldl, oldt);
            isBottom = false;
            currentY = t;
        }
    }

    public boolean isPullDownEnable() {
        return pullDownEnable;
    }

    public void setPullDownEnable(boolean pullDownEnable) {
        this.pullDownEnable = pullDownEnable;
    }

    public boolean isPullUpEnable() {
        return pullUpEnable;
    }

    public void setPullUpEnable(boolean pullUpEnable) {
        this.pullUpEnable = pullUpEnable;
    }
}
